from anole.utils.patterns.Singleton import Singleton
from anole import AnoleLog
from anole import AnoleError
import threading,socket
import random
import time
class DnsStatus:
	OK=0
	FAIL=1
class DnsError(AnoleError):pass
class SimpleDns(Singleton):
	def __init__(self):
                self._hostMap={
			}
                self._lock=threading.Lock()
		self._log=AnoleLog().log


        def resolve_host(self,strHost):
		self._log('dns::resolve',AnoleLog.LEVEL_DEBUG)

		self._lock.acquire()
		ips=self._hostMap.get(strHost,None)
		self._lock.release()
		if ips==None:
			try:
				t=socket.gethostbyname_ex(strHost)
			except:
				time.sleep(2)
				try:
					t=socket.gethostbyname_ex(strHost)
				except:
					raise DnsError('dns failed')
				
			ips=t[2]
			self._lock.acquire()
			self._hostMap[strHost]=ips
			self._lock.release()
		
		self._log('dns::ok',AnoleLog.LEVEL_DEBUG)
		num=len(ips)
		if num==1:
			return ips[0]
		else:
			i=random.randint(0,num-1)
			return ips[i]

